import type { TFunction } from 'i18next';
import type { RouteObject } from 'react-router-dom';

type FlatRoute = {
  name?: string;
  path: string;
};

interface SimpleRoute {
  key: string;
  children?: SimpleRoute[];
  title?: string;
}

const flattenLeafRoutes = (routes: RouteObject[]) => {
  const flat: FlatRoute[] = [];
  for (const route of routes) {
    if (route.children?.length) {
      flat.push(...flattenLeafRoutes(route.children));
    } else {
      if (route.path) {
        const isHasIndex = Boolean(route.children?.[0]?.index);
        if (isHasIndex || !route.children || route.children?.length < 1) {
          flat.push({
            name: route.id, // 根据需要保存 name，这里拿 route.id
            path: route.path, // path 可能为空字符串或undefined，统一成''
          });
        }
      }
    }
  }
  return flat;
};

/**
 * 判断是否是路由组，约定以 `(` 开头，以 `)` 结尾的是路由组
 * @returns
 */
const isRouteGroup = (routeId?: string) => {
  if (!routeId) return false;
  return routeId.endsWith(')');
};

/**
 * 过滤并展开路由数组，同时过滤掉handle.constant为true的路由，保留name,path,childred
 * @param routes
 * @param t
 * @returns
 */
const filterAndFlattenRoutes = (routes: RouteObject[], t: TFunction): SimpleRoute[] => {
  const result: SimpleRoute[] = [];
  for (const route of routes) {
    if (route.handle?.constant || route.index || (route.children?.[0]?.index && route.children[0].handle?.constant)) {
      continue;
    }

    if (isRouteGroup(route.id)) {
      if (route.children && route.children.length > 0) {
        const flattenedChildred = filterAndFlattenRoutes(route.children, t);
        result.push(...flattenedChildred);
      }
    } else {
      const newRoute: SimpleRoute = {
        key: route.path || '',
        title: t(`route.${route.id}`),
      };
      if (route.children && route.children.length > 0) {
        newRoute.children = filterAndFlattenRoutes(route.children, t);
      }
      result.push(newRoute);
    }
  }
  return result;
};

const getFlatBaseRoutes = (routes: FlatRoute[], t: TFunction) => {
  return routes.map(({ name, path }) => ({
    label: t(`route.${name}`),
    value: path,
  }));
};

const getBaseChildrenRoutes = (routes: RouteObject[]) => {
  const baseRoutes = routes[0].children?.find((item) => item.id === '(base)')?.children;
  return baseRoutes || [];
};

export { flattenLeafRoutes, filterAndFlattenRoutes, getFlatBaseRoutes, getBaseChildrenRoutes };
